package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.RoleMapper;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


@Service(interfaceClass = RoleService.class)
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    /**
     * 为新增角色添加角色数据和两个中间表数据
     * 注意主键回显
     * @param role
     * @param permissionIds
     */
    @Override
    public void add(Role role, Integer[] permissionIds,Integer[] menuIds) {
        roleMapper.add(role);
        roleMapper.setRoleAndPermission(role.getId(),permissionIds);
        roleMapper.setRoleAndMenu(role.getId(), menuIds);
    }

    /**
     * 查询角色数据
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //使用mybatis的分页插件,查询语句会自动拦截，所以顺序不会变
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        List<Role> roleList = roleMapper.findByCondition(queryPageBean.getQueryString());
        PageInfo<Role> pageInfo = new PageInfo<>(roleList);

        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 根据id查询角色
     *
     * @param id
     * @return
     */
    @Override
    public Role findById(Integer id) {
        return roleMapper.findById(id);
    }

    /**
     * 从中间表获取该角色拥有的权限id
     *
     * @param id
     * @return
     */
    @Override
    public List<Integer> findPermissionIdsByRoleId(Integer id) {
        return roleMapper.findPermissionIdsByRoleId(id);
    }

    /**
     * 编辑角色数据
     *
     * @param role
     * @param permissionIds
     */
    @Override
    public void edit(Role role, Integer[] permissionIds,Integer[] menuIds) {
        roleMapper.updateByRole(role);
        roleMapper.clearRoleAndPermissionByRoleId(role.getId());
        roleMapper.setRoleAndPermission(role.getId(),permissionIds);
        roleMapper.clearRoleAndMenuByRoleId(role.getId());
        roleMapper.setRoleAndMenu(role.getId(), menuIds);

    }

    /**
     * 删除角色数据
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        roleMapper.clearRoleAndPermissionByRoleId(id);
        roleMapper.clearRoleAndMenuByRoleId(id);
        roleMapper.deleteById(id);
    }

    /**
     * 查询所有角色数据
     *
     * @return
     */
    @Override
    public List<Role> findAll() {
        return roleMapper.findAll();
    }

}
